<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <el-tabs v-model="activeName">
          <!-- 角色管理 -->
          <el-tab-pane label="角色管理" name="first">
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <el-col>
                <el-button size="small" type="primary" @click="showDialog = true">新增角色</el-button>
              </el-col>
            </el-row>

            <el-table border="" :data="roleList" style="width: 100%">
              <el-table-column type="index" label="序号" width="60px" align="center">
                <!-- <template>
                  {{ scope.index+1 }}
                </template> -->
              </el-table-column>
              <el-table-column prop="name" label="角色名" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="text" @click="editPerm(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="text" @click="editRole(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="text" @click="deleteRole(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="end" align="middle" style="height: 60px;">
              <el-pagination
                layout="total,sizes,prev, pager, next,jumper"
                :total="page.total"
                :page-sizes="[2,5,10,20]"
                :current-page="page.page"
                :page-size="page.pagesize"
                @current-change="currentChange"
                @size-change="sizeChange"
              />
            </el-row>
          </el-tab-pane>
          <!-- 公司信息 -->
          <el-tab-pane label="公司设置" name="second">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="企业名称">
                <el-input v-model="companyList.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="企业地址">
                <el-input v-model="companyList.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="企业电话">
                <el-input v-model="companyList.companyPhone" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyList.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyList.remarks" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <el-dialog :title="roleForm.id?'编辑角色':'新增角色' " :visible="showDialog" @close="btnCancel">
          <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="roleForm.description" />
            </el-form-item>
          </el-form>
          <!-- 底部 -->
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" @click="btnCancel">取消</el-button>
              <el-button size="small" type="primary" @click="btnOK">确定</el-button>
            </el-col>
          </el-row>
        </el-dialog>
        <el-dialog title="分配权限" :visible="showPermDialog" @close="btnCancelPerm">
          <el-tree
            ref="tree"
            :default-expand-all="true"
            :show-checkbox="true"
            :check-strictly="true"
            node-key="id"
            :default-checked-keys="checkList"
            :data="permList"
            :props="{label:'name'}"
          />

          <el-row slot="footer">
            <el-button size="small" @click="btnCancelPerm">取消</el-button>
            <el-button size="small" type="primary" @click="btnOKPerm">确定</el-button>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getPermissionList } from '@/api/permisson'
import { convertTreeData } from '@/utils'
import { assignPerm } from '@/api/setting'
import { getRoleList, getCompany, deleteRole, getRoleDetail, updateRole, addRole } from '@/api/setting'
export default {
  data() {
    return {
      showPermDialog: false,
      showDialog: false, // 对话框控制
      activeName: 'first', // tab栏默认显示
      roleList: [], // 角色数据
      companyList: [], // 公司数据
      roleForm: {}, // 对话框数据
      permList: [],
      checkList: [],
      userId: '',
      page: { // 分页控制
        page: 1, // 页码
        pagesize: 5, // 页显示数
        total: 0 // 总条数
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  watch: {
    companyId: {
      handler() {
        // 判断当前的 companyId 是否存在
        if (this.companyId) {
          this.getCompany() // 获取公司数据
        }
      },
      immediate: true // 必须执行一次
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.roleList = rows // 角色数据
      this.page.total = total // 共多少条数据
    },
    async getCompany() {
      const data = await getCompany(this.companyId)
      this.companyList = data // 公司数据
    },
    async deleteRole(id) {
      try {
        await this.$confirm('确认删除该角色吗')
        await deleteRole(id) // 删除角色
        this.getRoleList() // 重新获取角色
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      this.roleForm = await getRoleDetail(id) //  先获取角色信息回显 避免页面闪烁
      this.showDialog = true // 显示对话框
    },
    async btnOK() {
      try {
        const isValidate = await this.$refs.roleForm.validate() // 验证对话框
        if (isValidate) {
          if (this.roleForm.id) {
            await updateRole(this.roleForm) // 更新角色数据
            this.$message.success('编辑成功')
          } else {
            await addRole(this.roleForm)
            this.$message.success('添加成功')
          }
          this.getRoleList() // 重新获取角色
          this.showDialog = false // 隐藏对话框
        }
      } catch (error) {
        console.log(error)
      }
    },
    currentChange(page) {
      this.page.page = page // 分页插件页码改变
      this.getRoleList()// 重新加载角色
    },
    sizeChange(pageSize) {
      this.page.pagesize = pageSize // 分页插件页显示数改变
      this.getRoleList() // 重新加载角色
    },
    btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields() // 移除校验
      this.showDialog = false // 对话框取消按钮右上角X
    },
    async editPerm(id) {
      this.userId = id
      const data = await getPermissionList()
      this.permList = convertTreeData(data, '0')
      const { permIds } = await getRoleDetail(id)
      this.checkList = permIds
      console.log(this.checkList)
      // console.log(this.$refs.tree.getCheckedKeys())
      this.showPermDialog = true
    },
    async btnOKPerm() {
      const data = {
        id: this.userId, permIds: this.$refs.tree.getCheckedKeys()
      }
      await assignPerm(data)
      this.$message.success('分配权限成功')
      this.showPermDialog = false
      console.log(this.$refs.tree.getCheckedKeys())
    },
    btnCancelPerm() {
      this.showPermDialog = false
    }

  }
}
</script>

<style lang="stylus">

</style>
